<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Schema;

class CreateSummyTable extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'summy:table {tableName} {fields*} {--force}';

    /**
     * The filesystem instance.
     *
     * @var \Illuminate\Filesystem\Filesystem
     */
    protected $files;


    //文件数组
    protected $fileArr=[];

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'create summy table';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Filesystem $files)
    {
        parent::__construct();
        $this->files = $files;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $table = $this->argument('tableName');
        $fields = $this->argument('fields');

        $isForce = $this->option('force');

        $this->createHourTable($table, $fields);
        $this->createMonthTable($table, $fields);

        // dd($this->fileArr);

        foreach($this->fileArr as $file) {
            $this->call('migrate', [
                '--path'=>'database/migrations/'.$file,
                '--force'=>$isForce
            ]);
        }

    }


    /**
     * 生成统计字段
     */
    protected function formatFields($fields, $type) {
        $result = [
            '$table->integer("pdi_index")->nullable(false)->comment("设备编号");',
            '$table->date("at_date")->nullable(false)->comment("日期");',
          //  '$table->integer("company_id")->nullable(false)->comment("公司编号");',
          //  '$table->integer("site_id")->nullable(false)->comment("站点编号");',
        ];
        
        $this->generateFields($fields, $result);

        if($type=='hour') {
            $result[] = '$table->integer("hour")->nullable(false)->default(0);';
            array_unshift($result, '$table->increments("id")->nullable(false)->comment("");');
        }
        $result[] = '$table->integer("num")->nullable(false)->default(1);';

        if($type=='month') {
            $result[] = '$table->primary(["pdi_index", "at_date"]);';
        }
        return implode(PHP_EOL, $result);
    }

    //生成迁移字段
    protected function generateFields($fields, &$result) {
        $str='$table->decimal("%s", 9, 2)->nullable(false)->default(0);';
        foreach($fields as $k) {
            $result[] = \sprintf($str, $k);
        }
    }

    /**
     * 获取表格内容
     */
    protected function getTableFile($isCreate=true) {
        $fileName = $isCreate?'table':'updateTable';
        $table = $this->files->get(__DIR__."/stubs/{$fileName}.sub");
        $file = $this->files->get(__DIR__.'/stubs/create.sub');

        return [$table, $file];
    }

    /**
     * 获取类名
     */
    protected function getClassName($name)
    {
        return Str::studly($name);
    }


    /**
     * 文件路径
     */
    protected function getMigrationPath($tableName)
    {
        $path = $this->laravel['path.database'].'/migrations/';

        $file = date('Y_m_d_His').'_'.$tableName.'.php';


        $this->fileArr[$tableName] = $file;

        return $path.$file;
    }

    //添加时间后缀
    protected function formatFileName($str) {
        return $str.'_s'.Date('His');
    }

    /**
     * 生成表格
     */
    protected function createTable($tableName, $fields, $type="hour") {
        list($table, $file) = $this->getTableFile();

        $filename = $this->formatFileName($tableName);

        $class=$this->getClassName($filename);

        $fields = $this->formatFields($fields, $type);

        $tableContent = str_replace('%tableName', $tableName, $table);
        $tableContent = str_replace('%fields', $fields, $tableContent);

        $fileContent = str_replace('DummyClass', $class, $file);

        $fileContent = str_replace('%CreateTable%', $tableContent, $fileContent);

        $fileContent = str_replace('%dropTable%', "Schema::dropIfExists('$tableName');", $fileContent);

        $this->files->put($this->getMigrationPath($filename), $fileContent);
    }

    /**
     * 更新表格
     */
    protected function updateTable($tableName, $fields) {
        if(!$fields)return;

        list($table, $file) = $this->getTableFile(false);

        $dropTableColumn = $table;

        $filename = $this->formatFileName($tableName);

        $class=$this->getClassName($filename);

        $resultField = [];

        $this->generateFields($fields, $resultField);

        $strFields = implode(PHP_EOL, $resultField);

        $tableContent = str_replace('%tableName', $tableName, $table);
        $tableContent = str_replace('%fields', $strFields, $tableContent);

        $fileContent = str_replace('DummyClass', $class, $file);

        $fileContent = str_replace('%CreateTable%', $tableContent, $fileContent);


        $dropTableColumn = str_replace('%tableName', $tableName, $dropTableColumn);

        $dropFields = '"'.implode('", "', $fields).'"';

        $dropTableColumn = str_replace('%fields', '$table->dropColumn(['.$dropFields.']);', $dropTableColumn);

        $fileContent = str_replace('%dropTable%', $dropTableColumn, $fileContent);

        $this->files->put($this->getMigrationPath($filename), $fileContent);
    }


    //是否更新
    protected function hasUpdate($tableName) {
        return Schema::hasTable($tableName);;
    }

    //已存在的字段
    protected function getHasFields($tableName, $fields) {
        $columns = Schema::getColumnListing($tableName);
       // $del = array_diff($columns, $fields);
        $add = array_diff($fields, $columns);

        return $add;
    }

    /**
     * 创建小时统计表
     */
    protected function createHourTable($name, $fields)
    {
        $tableName = "t_hour_{$name}";

        $isUpdate = $this->hasUpdate($tableName);

        if($isUpdate) {
            $addFields = $this->getHasFields($tableName, $fields);
            $this->updateTable($tableName, $addFields);
            return;
        }
        $this->createTable($tableName, $fields, 'hour');
    }

    /**
     * 创建每月统计表
     */
    protected function createMonthTable($name, $fields)
    {
        $tableName = "t_month_{$name}";

        $isUpdate = $this->hasUpdate($tableName);

        if($isUpdate) {
            $addFields = $this->getHasFields($tableName, $fields);
            $this->updateTable($tableName, $addFields);
            return;
        }
        $this->createTable($tableName, $fields, 'month');
    }
}
